/**
 * Company : SIANGKLOM.
 * Created By : Chatree Siangklom
 * Created On : Sep 2, 2013  12:05:41 PM 
 * e-Mail : dr_chatree@hotmail.com
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : com.tis.interfaces.controller.commons
 * File Name : CommonController.java
 * TODO
 */
package com.tis.interfaces.controller.commons;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import promis.utility.CommonService;

import com.tis.database.entitys.security.AdUserLogin;
import com.tis.database.entitys.security.AdUserLoginHistory;
import com.tis.database.entitys.staging.ApplicationLoging;
import com.tis.database.entitys.staging.XmlResultback;
import com.tis.database.services.security.IAdUserLoginHistoryServices;
import com.tis.database.services.security.IAdUserLoginServices;
import com.tis.database.services.staging.IApplicationLogingServices;
import com.tis.encryption.AESUrlencrp;
import com.tis.encryption.AESencrp;
import com.tis.interfaces.apps.SESSION_MANAGE;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Sep 2, 2013 : 12:05:41 PM 
 * CreateBy=Chatree Siangklom
 * TODO
 */
public class CommonController {
	
	private static final Logger log = LoggerFactory.getLogger(CommonController.class);
	
	/**
	 * Date =Sep 2, 2013 : 12:05:41 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	public CommonController()  {
		
	}
	
	HttpServletRequest request_gol;	
	@Autowired IAdUserLoginServices iAdUserLoginServices;		
	@Autowired IApplicationLogingServices iApplicationLogingServices;
	
	/**
	 * Date =Oct 18, 2013 : 4:04:31 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param applicationLoging
	 * @throws Exception
	 */
	protected void KeepLogs(ApplicationLoging applicationLoging) {
		try{
			
			BigDecimal id = iApplicationLogingServices.NextSequence();	
			
			if(request_gol != null){
				
				applicationLoging.setUri(request_gol.getServletPath());
				
				try{
					Enumeration headerNames = request_gol.getHeaderNames();
					while(headerNames.hasMoreElements()) {
						String paramName = CommonService.IsNullRString(headerNames.nextElement()).toLowerCase();
						String paramValue = CommonService.IsNullRString(request_gol.getHeader(paramName)).toLowerCase();
						if(paramName.equals("host"))
							applicationLoging.setHostName(paramValue);
					}
				}catch(Exception e){
					e.printStackTrace();
					log.error(e.getMessage());
				}
			}
						
			if(CommonService.IsNull(applicationLoging.getCreatedon()))
				applicationLoging.setCreatedon(iApplicationLogingServices.getCurrentDatabaseDate());
			
			applicationLoging.setMsgDesc(CommonService.CutString(applicationLoging.getMsgDesc(), 2900));
			applicationLoging.setMsgAltDesc(CommonService.CutString(applicationLoging.getMsgAltDesc(), 2900));
			
			applicationLoging.setUpdatedon(iApplicationLogingServices.getCurrentDatabaseDate());
			applicationLoging.setId(CommonService.IsNullRNull(id));
			iApplicationLogingServices.saveOrUpdate(applicationLoging);
			
		}catch(Exception e){
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public String Encoding(String text) throws Exception{
		return (CommonService.IsNull(text) ? null :  new String(text.getBytes(AESUrlencrp.decrypt("naP6uwrQWi7gTewV3LJd8h9xgQ{||9||}zXsVAPGq7tL5JWBY{||4||}")), AESUrlencrp.decrypt("xLblxcO3GfgVz360sTknNPU68fJ0SNoNJpZffnjfQEw{||4||}")));
	}	
	
	/**
	 * 
	 * Date =Sep 2, 2013 : 1:00:53 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param request
	 * @return true = still login session, false = not still login session
	 * @throws Exception
	 */
	public boolean UserLoginValidation(HttpServletRequest request) throws Exception{
		try {
			
			request_gol = request;
			
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", "UserLoginValidation", getCurrentAppsInstanceNo()));
			HttpSession session = request.getSession();
			Object objjSession = session.getAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin);
			
			if(objjSession != null) {
				
				AdUserLogin adUserLogin = (AdUserLogin)objjSession;
				String userLogin = CommonService.IsNullRString(adUserLogin.getUserLogin());
				String userPassword = CommonService.IsNullRString(adUserLogin.getPassword());
				
				AdUserLogin adUserLogin1 = iAdUserLoginServices.findByUserPassword(userLogin, userPassword);
				
				if(adUserLogin != null && adUserLogin1 != null) {
					if(!CommonService.IsNull(adUserLogin.getUserLogin()) && !CommonService.IsNull(adUserLogin.getPassword()) && !CommonService.IsNull(adUserLogin1.getUserLogin()) && !CommonService.IsNull(adUserLogin1.getPassword())) {
						if(adUserLogin.getUserLogin().equals(adUserLogin1.getUserLogin()) && adUserLogin.getPassword().equals(adUserLogin1.getPassword())) {
							//return "redirect:/index.htm";	
							
							KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "S", "SUCCESS", "UserLoginValidation UserLogin:" + adUserLogin1.getUserLogin(), getCurrentAppsInstanceNo()));
							return true;
						}else  KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "F", "FAIL", "UserLoginValidation", getCurrentAppsInstanceNo()));
					}else  KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "F", "FAIL", "UserLoginValidation", getCurrentAppsInstanceNo()));
				}else KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "F", "Find not found or User Session null", "UserLoginValidation", getCurrentAppsInstanceNo()));
			}
			//if non connitional set value to NULL
			session.setAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin, null);
		}catch(Exception e) {
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", e.getMessage(), "UserLoginValidation", getCurrentAppsInstanceNo()));
		}		
		return false;
	}
	
	public AdUserLogin AuthenOfPromis(String interfacekey)  throws Exception {		
		try{
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", "Authentication Key:" + interfacekey, getCurrentAppsInstanceNo()));
			
			String [] strVal = AESUrlencrp.decrypt(interfacekey).split("\\*");
			String user = strVal[0];
			String password = strVal[1];
				
			log.info("AuthenOfPromis user=" + user + "//password=" + password);	
			
			AdUserLogin adUserLogin = iAdUserLoginServices.findByUserPassword(user, password);
			if(adUserLogin != null){
				if(AESencrp.decrypt(CommonService.IsNullRString(adUserLogin.getUserLogin())).equals("INTERFACE"))
				{
					KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "S", "SUCCESS", "Authentication", getCurrentAppsInstanceNo()));
					return adUserLogin;
				}else {
					KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "F", "FAIL", "Authentication", getCurrentAppsInstanceNo()));
				}
			}			
		}catch(Exception e){
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", e.getMessage(), "Authentication", getCurrentAppsInstanceNo()));
			e.printStackTrace();
			throw e;
		}		
		return null;
	}
	
	/**
	 * 
	 * Date =Sep 26, 2013 : 1:46:00 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public boolean UserJspLoginValidation(HttpServletRequest request) throws Exception {
		
		HttpSession session = request.getSession();
		Object objjSession = session.getAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin);
		if(objjSession != null) {
			AdUserLogin adUserLogin = (AdUserLogin)objjSession;
			String userLogin = CommonService.IsNullRString(adUserLogin.getUserLogin());
			String userPassword = CommonService.IsNullRString(adUserLogin.getPassword());
			if(!CommonService.IsNull(userLogin) && !CommonService.IsNull(userPassword)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 
	 * Date =Sep 26, 2013 : 1:45:56 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public AdUserLogin GetAdUserLoginSession(HttpServletRequest request) throws Exception 
	{
		try {
			
			HttpSession session = request.getSession();
			Object objjSession = session.getAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin);
			if(objjSession != null) {
				AdUserLogin adUserLogin = (AdUserLogin)objjSession;
				String userLogin = CommonService.IsNullRString(adUserLogin.getUserLogin());
				String userPassword = CommonService.IsNullRString(adUserLogin.getPassword());
				if(!CommonService.IsNull(userLogin) && !CommonService.IsNull(userPassword)) {
					return adUserLogin;
				}
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			log.error(ex.getMessage());
		}
		return null;
	}
	
	@Autowired
	private  IAdUserLoginHistoryServices iAdUserLoginHistoryServices;
	
	/**
	 * 
	 * Date =Sep 26, 2013 : 4:32:19 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param request
	 * @param adUserLogin
	 * @throws HibernateException
	 * @throws Exception
	 */
	protected void UpdateAdUserLogin(HttpServletRequest request, AdUserLogin adUserLogin) throws HibernateException, Exception {
		try {
			if(adUserLogin != null) {
				BigDecimal lastedAccessKey = iAdUserLoginHistoryServices.NextSequence();
				String lastedIpAccess = CommonService.IsNullRString(request.getRemoteAddr());
				adUserLogin.setLastedAccess(new Date());			
				adUserLogin.setLastedIpAccess(lastedIpAccess);
				adUserLogin.setLastedAccessKey(CommonService.IsNullRString(lastedAccessKey));
				
				iAdUserLoginServices.StampLastedUserAccess(adUserLogin);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * Date =Sep 26, 2013 : 1:46:07 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param request
	 * @throws Exception
	 */
	synchronized
	public void UserAccessTime(HttpServletRequest request, String pageName)  throws Exception {
		try {
			
			String accept = null;
			String acceptLanguage = null;
			String userAgent = null;
			String acceptEncoding = null;
			String host = null;
			String dnt = null;
			String connection = null;
			String cookie = null;
			String clientIp = CommonService.IsNullRNull(request.getRemoteAddr());
			String servlertPath = request.getServletPath();
			
			Enumeration headerNames = request.getHeaderNames();
			while(headerNames.hasMoreElements()) {
				String paramName = CommonService.IsNullRString(headerNames.nextElement()).toLowerCase();
				String paramValue = CommonService.IsNullRString(request.getHeader(paramName)).toLowerCase();
				if(paramName.equals("accept"))
					accept = paramValue;
				else if(paramName.equals("accept-language"))
					acceptLanguage = paramValue;
				else if(paramName.equals("user-agent"))
					userAgent = paramValue;
				else if(paramName.equals("accept-encoding"))
					acceptEncoding = paramValue;
				else if(paramName.equals("host"))
					host = paramValue;
				else if(paramName.equals("dnt"))
					dnt = paramValue;
				else if(paramName.equals("connection"))
					connection = paramValue;
				else if(paramName.equals("cookie"))
					cookie = paramValue;
				else {
					accept="";acceptLanguage="";userAgent="";acceptEncoding="";host="";dnt="";connection="";cookie="";
				}
			}

			AdUserLogin adUserLogin = this.GetAdUserLoginSession(request);
			
			try {
				AdUserLoginHistory model = new AdUserLoginHistory();
				
				BigDecimal pkId = iAdUserLoginHistoryServices.NextSequence("AD_USER_LOGIN_HISTORY");
				
				model.setPkId(pkId);	
				
				model.setAccept(accept);
				model.setAcceptLanguage(acceptLanguage);
				model.setClientIp(clientIp);
				model.setAcceptEncoding(acceptEncoding);
				model.setConnection(connection);
				model.setCookie(cookie);
				model.setDnt(dnt);
				model.setHost(host);
				model.setUserAgent(userAgent);
				model.setCreatedOn(new Date());
				model.setAddress(servlertPath);
				model.setUserAccessPageName(pageName);				
				
				
				if(adUserLogin != null) {
					model.setCreatedBy(adUserLogin.getUserLogin());
					model.setAdUserLoginId(adUserLogin.getPkId());
					
					if(!CommonService.IsNull(adUserLogin.getUserLogin()))
						model.setUserLogin(adUserLogin.getUserLogin());
					
					if(!CommonService.IsNull(adUserLogin.getPassword()))
						model.setPassword(adUserLogin.getPassword());
					
					if(!CommonService.IsNull(adUserLogin.getLastedAccessKey()))
						model.setInstanceNo(adUserLogin.getLastedAccessKey());
					
				}
				
								
				iAdUserLoginHistoryServices.saveOrUpdate(model);
				log.info("AdUserLoginHistory.toString =" + model.toString());
				
			}catch(Exception ex) {
				ex.printStackTrace();
				log.error(ex.getMessage());
			}
			
			/*
			String ip = request.getHeader("X-Forwarded-For");  
			     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			         ip = request.getHeader("Proxy-Client-IP");  
			     }  
			     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			         ip = request.getHeader("WL-Proxy-Client-IP");  
			     }  
			     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			         ip = request.getHeader("HTTP_CLIENT_IP");  
			     }  
			     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			         ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
			     }  
			     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			         ip = request.getRemoteAddr();  
			     }
		     */
			
		}catch(Exception e) {
			e.printStackTrace();
		}		
	}
	

	protected String Fullname(AdUserLogin adUserLogin) throws Exception{
		String temp = "";
		try {
			
			if(adUserLogin != null) {
				if(!CommonService.IsNull(adUserLogin.getFirstName()))
					temp = CommonService.IsNullRString(adUserLogin.getFirstName());
				
				if(!CommonService.IsNull(adUserLogin.getLastName()))
					temp += " " + CommonService.IsNullRString(adUserLogin.getLastName());
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		
		return temp;
	}
	
	protected String Fullname(HttpServletRequest request) throws Exception{
		String temp = "";
		try {
			AdUserLogin adUserLogin = GetAdUserLoginSession(request);
			
			if(adUserLogin != null) {
				if(!CommonService.IsNull(adUserLogin.getFirstName()))
					temp = CommonService.IsNullRString(adUserLogin.getFirstName());
				
				if(!CommonService.IsNull(adUserLogin.getLastName()))
					temp += " " + CommonService.IsNullRString(adUserLogin.getLastName());
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		
		return temp;
	}
	
	
	public Date ConvertStringToDateTime(String strDate){
//		strDate = strDate.replace(" ", "");
//		String [] temp = strDate.split("\\|");
//		String [] date = temp[0].split("\\-");
//		String [] time = temp[1].split("\\:");
//		
//		System.out.println(temp[0]); //Date
//		System.out.println(temp[1]); //Time
//		
//		System.out.println(date[0]); //YYYY
//		System.out.println(date[1]); //MM		
//		System.out.println(date[2]); //DD
//		int day = Integer.parseInt(date[2]);
//		int month = Integer.parseInt(date[1]);
//		int year = Integer.parseInt(date[0]);
//		
//		System.out.println(time[0]); //H24
//		System.out.println(time[1]); //MI
//		System.out.println(time[2]); //SS
//		
//		int H24 = Integer.parseInt(time[0]);
//		int Mi = Integer.parseInt(time[1]);
//		int Sec = Integer.parseInt(time[2]);
		
		if(CommonService.IsNull(strDate)) return null;
		
		DateFormat formatter; 
		Date date = null;
		formatter = new SimpleDateFormat("dd-MM-yyyy");
		try {
			  
			date = (Date)formatter.parse(strDate);
			
		} catch (ParseException e) {
			System.err.println(e.getMessage());
		}
		
		return date;
	}
	
	
	private BigDecimal currentAppsInstanceNo;

	/**
	 * @return the currentAppsInstanceNo
	 * Date =Oct 18, 2013 : 4:17:11 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	public String getCurrentAppsInstanceNo() {		
		
		return CommonService.IsNullRNull(currentAppsInstanceNo);
	}	
	
	/**
	 * Date =Oct 18, 2013 : 4:54:19 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @return
	 */
	public void setCurrentAppsInstanceNo() {
		try{
			currentAppsInstanceNo = iApplicationLogingServices.NextInstanceNo();
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	
	protected HttpEntity<byte[]> ToXml(XmlResultback xmlResultback) {
		try{
			String xml = xmlResultback.GennerateToXml(); 
			log.info("xml=" + xml);
		    byte[] documentBody = xml.getBytes();

		    HttpHeaders header = new HttpHeaders();
		    header.setContentType(new MediaType("application", "xml"));
		    header.setContentLength(documentBody.length);
		    
		    return new HttpEntity<byte[]>(documentBody, header);
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return null;
	}
}
